import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtCustomPayload } from 'src/types';
import { RedisService } from '../redis/redis.service';
import { ACCESS_TOKEN_EXPIRATION_TIME, USER_ACCESS_TOKEN_KEY, USER_ACCESS_TOKEN_TYPE } from './config';

@Injectable()
export class JwtConfigService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly redisService: RedisService,
  ) {}

  /** 生成token */
  public async generateToken(payload: JwtCustomPayload) {
    const accessToken = `${USER_ACCESS_TOKEN_TYPE}${this.jwtService.sign(payload)}`;
    // 存redis
    await this.redisService.setStringWithEx(
      this.getAccessTokenKey(payload.userId),
      ACCESS_TOKEN_EXPIRATION_TIME,
      accessToken,
    );
    return accessToken;
  }

  /** 得到 token key */
  getAccessTokenKey(userId: number) {
    return `${USER_ACCESS_TOKEN_KEY}:${userId}`;
  }
}
